//
//  MineInfoEditWXQRCodeViewController.m
//  Btpin
//
//  Created by Vic on 2019/3/18.
//  Copyright © 2019 Vic. All rights reserved.
//

#import "MineInfoEditWXQRCodeViewController.h"
#import <Photos/Photos.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>

@interface MineInfoEditWXQRCodeViewController ()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, PSSingleRowViewDelegate>
{
    PSCell *wxIDCell;
    PSSingleRowView *headerPickerView;
    
    UIButton *updateBtn;
}
@end

@implementation MineInfoEditWXQRCodeViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (headerPickerView) {
        headerPickerView.hidden = YES;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
}
- (void)initUI {
    self.navigationItem.title = @"微信二维码";
    
    UIButton *okBtn = [UIToolsControl initButtonWithFrame:CGRectMake(WIDTH-50*Scale, HeightOfStatusBar+3*Scale, 50*Scale, 36*Scale) imageName:nil target:self action:@selector(okBtnTap) title:@"确定" titleColor:THEMECOLOR_OF_ORANGE];
    okBtn.titleLabel.font = Font(Font_15);
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:okBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    
    NSMutableArray *headerArray = [NSMutableArray arrayWithCapacity:0];
    PublicCategoryElementModel *model1 = [[PublicCategoryElementModel alloc] init];
    [model1 setValuesForKeysWithDictionary:@{@"id":@"0", @"name":@"拍摄"}];
    [headerArray addObject:model1];
    PublicCategoryElementModel *model2 = [[PublicCategoryElementModel alloc] init];
    [model2 setValuesForKeysWithDictionary:@{@"id":@"1", @"name":@"相册"}];
    [headerArray addObject:model2];
    headerPickerView = [[PSSingleRowView alloc] initWithData:headerArray target:self];
    headerPickerView.hidden = YES;
    
    
    wxIDCell = [[PSCell alloc] initWithFrame:CGRectMake(30*Scale, 10*Scale, WIDTH-60*Scale, PSCellHeight) title:@"微信号" text:nil placeholder:@"请输入" cellType:PSCellTypeOfWriteonly];
    [self.view addSubview:wxIDCell];
    if (self.wxID) {
        wxIDCell.textField.text = self.wxID;
    }
    
    UILabel *topLbl = [UIToolsControl initLabelWithFrame:CGRectMake(StartX(wxIDCell), EndY(wxIDCell)+10*Scale, 200, 40*Scale) text:@"微信二维码上传：" textColor:THEMECOLOR_OF_TEXT_333333 font:Font_13];
    [self.view addSubview:topLbl];
    
    updateBtn = [UIToolsControl initButtonWithFrame:CGRectMake(StartX(wxIDCell), EndY(topLbl), 110*Scale, 110*Scale) imageName:nil target:self action:@selector(updateBtnTap) title:nil titleColor:nil];
    [updateBtn setBackgroundImage:[UIImage imageNamed:@"update_icon"] forState:UIControlStateNormal];
    [self.view addSubview:updateBtn];
    if (self.wxURL && self.wxURL.length) {
        [updateBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.wxURL] forState:UIControlStateNormal];
        updateBtn.contentMode = UIViewContentModeScaleAspectFill;
    }
    
    UILabel *bottomLbl = [UIToolsControl initLabelWithFrame:CGRectMake(StartX(wxIDCell), EndY(updateBtn), WIDTH-39*Scale, 50*Scale) text:@"提示：上传微信二维码，可以生成自己的名片，建议上传" textColor:THEMECOLOR_OF_ORANGE font:Font_13];
    [self.view addSubview:bottomLbl];
}
- (void)updateBtnTap {
    if (wxIDCell.textField.isFirstResponder) {
        [wxIDCell.textField resignFirstResponder];
    }
    headerPickerView.hidden = NO;
}
- (void)psSingleRowViewCancel:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
}
- (void)psSingleRowViewOk:(PublicCategoryElementModel *)model PSSingleRowView:(PSSingleRowView *)psSingleRowView {
    psSingleRowView.hidden = YES;
    if ([model.id integerValue] == 1) { // 相册
        [self openPhotoLibrary];
    } else { // 拍摄
        [self openCamera];
    }
}
- (void)openCamera {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相机权限未开启" message:@"相机权限未开启，请进入系统【设置】>【隐私】>【相机】中打开开关,开启相机功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
}
- (void)openPhotoLibrary {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) { // 无权限
        CustomView *alertView = [[CustomView alloc] initWithTitle:@"相册权限未开启" message:@"相册权限未开启，请进入系统【设置】>【隐私】>【相册】中打开开关,开启相册功能" prompt:nil sureBtn:@"确定" cancleBtn:@"取消" size:170];
        alertView.resultIndex = ^(NSInteger index) { //回调---处理一系列动作
            if (index == 2) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
        };
        [alertView showXLAlertView];
    } else { // 有权限
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.navigationBar.translucent = NO;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:imagePicker animated:YES completion:^{
            NSLog(@"打开相册");
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSLog(@"finish..");
    UIImage *image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    SVPHUDShow;
    [DataToolsControl uploadImgType:UploadImgTypeOfWeixin image:image successBlock:^(NSDictionary *responseObject) {
        if ([responseObject[@"code"] integerValue] == 2000) {
            id data = responseObject[@"data"];
            NSString *path = data[@"url"];
            [self->updateBtn setBackgroundImage:image forState:UIControlStateNormal];
            if (self.delegate && [self.delegate respondsToSelector:@selector(mineInfoEditWXQRCodeViewControllerInfo:)]) {
                [self.delegate mineInfoEditWXQRCodeViewControllerInfoWXImgPath:path];
            }
            SVPHUDDismiss;
        } else {
            SVPHUDError(responseObject[@"msg"]);
        }
    } failurBlock:^(NSError *error) {
        SVPHUDError(@"上传失败，请重新操作");
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)okBtnTap {
    if (wxIDCell.textField.text.length>0) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(mineInfoEditWXQRCodeViewControllerInfo:)]) {
            [self.delegate mineInfoEditWXQRCodeViewControllerInfo:wxIDCell.textField.text];
            [self.navigationController popViewControllerAnimated:YES];
        }
    } else {
        SVPHUDError(WXIDOKAlertText);
        [wxIDCell.textField becomeFirstResponder];
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (wxIDCell.textField.isFirstResponder) {
        [wxIDCell.textField resignFirstResponder];
    }
}

@end
